/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package net.flowas.genericcrud.rest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import net.flowas.genericcrud.service.ViewConfig;

/**
 * REST Web Service.
 *
 * @author Administrator
 */
// @Path("i18n")
// @ApplicationScoped
public class I18nResource {
  
  enum Region {
    TABLE, NEW_FORM
  }
  private ViewConfig viewConfig;
  
  public void setViewConfig(ViewConfig viewConfig) {
	this.viewConfig = viewConfig;
}

/**
   * Retrieves representation of an instance of net.flowas.demo.rest.I18nResource
   *
   * @return an instance of java.lang.String
   */
  @GET
  @Path("/all/datas")
  @Produces(MediaType.APPLICATION_JSON)
  public Map<String, String> getJson() {
    return viewConfig.i18nToMap();
  }

  /**
   * 获取数据结构的字段的国际化名称.
   * @param modelName 模型
   * @param region 数据模型的展示区域
   */
  @GET
  @Path("/forModel/{modelType}/{region}")
  @Produces(MediaType.APPLICATION_JSON)
  public List<Map<String, Object>> columnDefs(@PathParam(CrudConstant.MODEL_TYPE) String modelName,
      @PathParam(CrudConstant.PARAM_REGION) String region) {
    List<Map<String, Object>> fields = viewConfig.columnDefs(modelName);
    if (fields == null) {
      fields = new ArrayList<>();
    }
    Region regionEnum = Region.valueOf(region);
    switch (regionEnum) {
      case TABLE:
        return fields;
      case NEW_FORM:
        return newFormModel(fields);
      default:
        break;
    }
    return fields;
  }

  private List<Map<String, Object>> newFormModel(List<Map<String, Object>> fields) {
    List<Map<String, Object>> list = new ArrayList<>();
    for (Map<String, Object> map : fields) {
      Map<String, Object> formField = new HashMap<>();
      formField.put("key", map.get("field"));
      String formType;
      if (map.containsKey("formType")) {
        formType = (String) map.get("formType");
      } else {
        formType = "input";
      }
      formField.put("type", formType);
      Map<String, Object> templateOptions = new HashMap<>();
      templateOptions.put("label", map.get("displayName"));
      formField.put("templateOptions", templateOptions);
      list.add(formField);
    }
    return list;
  }
}
